package com.dayu.finecomm.iot.device;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpRequestEncoder;
import io.netty.handler.codec.http.HttpResponseDecoder;
import io.netty.handler.ssl.SslHandler;

import java.util.concurrent.CountDownLatch;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dayu.finecomm.iot.handle.IotPlatSyncInboundHandler;

/**
 * IotPlat驱动, 处理IotPlat协议
 * 
 * @author XuJialiang
 * @since 2017-09-04 10:22:12
 * @version V1.0.0
 */
public class IotPlatSyncDevice extends ChannelInitializer<SocketChannel> {
	static Logger LOGGER = LoggerFactory.getLogger(IotPlatSyncDevice.class);

	/**
	 * SSL Context
	 */
	private final SSLContext mSSLCtx;

	/**
	 * SSL peer port
	 */
	@SuppressWarnings("unused")
	private final int mPort;

	/**
	 * 同步计数器
	 */
	private CountDownLatch mLathc;

	/**
	 * 消息处理Handler
	 */
	private IotPlatSyncInboundHandler mHandler;

	public IotPlatSyncDevice(CountDownLatch lathc, int port, SSLContext sslCtx) {
		mLathc = lathc;
		mPort = port;
		mSSLCtx = sslCtx;
	}

	@Override
	protected void initChannel(SocketChannel ctx) throws Exception {
		mHandler = new IotPlatSyncInboundHandler(mLathc);

		ChannelPipeline pipeline = ctx.pipeline();

		if (null != mSSLCtx) {
			SSLEngine sslEngine = mSSLCtx.createSSLEngine();
			sslEngine.setUseClientMode(true);
			pipeline.addLast(new SslHandler(sslEngine));
		}

		// pipeline.addLast(new IdleStateHandler(0, 0, 5));
		// pipeline.addLast(new DelimiterBasedFrameDecoder(81920,
		// Delimiters.lineDelimiter()));
		pipeline.addLast(new HttpResponseDecoder());
		pipeline.addLast(new HttpRequestEncoder());
		// pipeline.addLast(new HttpObjectAggregator(16 * 1024));
		pipeline.addLast(mHandler);
	}

	/**
	 * 获取IOT平台响应的结果
	 * 
	 * @return
	 */
	public String getServerResult() {
		return mHandler.getResult();
	}

	/**
	 * 获取IOT平台响应码
	 * 
	 * @return
	 */
	public int getServerCode() {
		return mHandler.getCode();
	}

	/**
	 * 重置同步锁
	 * 
	 * @param initLathc
	 *            同步计数器
	 */
	public void resetLathc(CountDownLatch initLathc) {
		mHandler.resetLatch(initLathc);
	}
}
